import message from './message_pb.js'

//
// let msg = new message.Message()
// msg.setGuid('asdasd')
// let bytes = msg.serializeBinary();
// message.Message.deserializeBinary(bytes)

/**
 * websocket与netty之间的通讯的客户端实现
 * 数据传输采用 google protocol buffer  协议
 * 详见
 */
class Im {

    constructor(){
        this.ws = null
    }



    /**
     * 初始化连接
     * @param path
     * @returns {Promise<any>}
     */
    init(path,onmessage) {
        return new Promise(((resolve, reject) => {
            this.ws = new WebSocket(path)
            //必须加上这一点 才能接受字符流消息
            this.ws.binaryType = "arraybuffer";
            this.ws.onopen = function () {
                resolve('ok')
            }

            this.ws.onmessage = function (evt) {
                let received_msg = evt.data;
                onmessage(received_msg)
            };

            this.ws.onclose = function (error) {
                reject('error:'+error)
                // 关闭 websocket
            };

            this.ws.onerror = function (error) {
                reject('error:'+JSON.stringify(error))
                console.log('连接失败')
            }


        }))
    }



    /**
     * 发送消息
     * @param msg
     */
    sendMsg(msg) {
        if (this.ws) {
            this.ws.send(msg)
        }
    }
}
export default new Im() //单例

// let im = new Im()
// im.init("ws://localhost:9090/ws").then(()=>{
//     let msg = new message.Message()
//     msg.setGuid('asdasd')
//     msg.setContent("你好")
//     let bytes = msg.serializeBinary();
//     message.Message.deserializeBinary(bytes)
//     im.sendMsg(bytes)
//
// })



